package com.yswee.framework.utils;

import java.lang.reflect.Field;

import com.yswee.framework.Application;

import android.app.Activity;
import android.content.Context;
import android.view.View;

import androidx.fragment.app.Fragment;

public class ViewInjectUtils {

	/**
	 * 注入
	 * @param obj
	 */
	public static void onInjectView(Object obj) {
		Class<?> clazz = obj.getClass();
		_onInjectView(clazz, obj, null);
	}
	
	/**
	 * 注入
	 * @param obj
	 */
	public static void onInjectView(Object obj, View view) {
		Class<?> clazz = obj.getClass();
		_onInjectView(clazz, obj, view);
	}
	
	private static void _onInjectView(Class<?> clazz, Object obj, View view) { 
		try {
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				try {
					if (field.isAnnotationPresent(ViewInject.class)) {
						ViewInject inject = field.getAnnotation(ViewInject.class);
						int id = inject.value();
						if(id == 0) {
							Context context = Application.get();
							id = context.getResources().getIdentifier(field.getName(), "id", context.getPackageName());
						}
						if (id != 0) {
							field.setAccessible(true);
							if(obj instanceof Activity) {
								field.set(obj, ((Activity) obj).findViewById(id));
							} else if(obj instanceof View) {
								field.set(obj, ((View) obj).findViewById(id));
							} else if(obj instanceof Fragment && view != null) {
								field.set(obj, view.findViewById(id));
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Class<?> superclazz = clazz.getSuperclass();
			String superclazzname = superclazz.getName().toLowerCase();
			if(superclazzname.startsWith("java") || superclazzname.startsWith("android")) {
				return;
			}
			_onInjectView(superclazz, obj, view);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}
	
}
